<?php
namespace app\admin\controller;
use app\common\model\Account;
use app\common\model\RoleModel;
use app\common\model\MenuModel;
use app\common\model\UserAttributesModel;
use app\common\model\RoleMenusModel;
use think\Validate;
use think\Db;
use think\Session;
use app\admin\library\account\MenuService;
use app\admin\library\account\SettingService;
use app\admin\library\account\RoleService;


class AccountController extends BaseController
{
    public function add()
    {
        return view();
    }
    public function handle()
    {
        //数据验证
        $data = input('post.');

        $validate = new Validate([
            ['account','require','账号必须'],
            ['password','require|min:6','密码必须|密码长度不能低于6位'],
            ['repassword','require','重复密码必须'],
            ['true_name','require','姓名必须'],
            ['role_id','require','请选择角色'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        if (Db::name('account')->where(['account'=>$data['account']])->find()){
            $this->error('账号已存在');
        }
        if ($data['password'] != $data['repassword']) {
            $this->error('两次输入的密码不一致');
        }
        $data['password'] = md5($data['password']);

        return Account::add($data,true);
    }
    /**
     * 创建团队账号
     * 
     */
    public function organizationAccount()
    {
        //数据验证
        $data = input('post.');
        $validate = new Validate([
            ['account','require','账号必须'],
            ['password','require|min:6','密码必须|密码长度不能低于6位'],
            ['repassword','require','重复密码必须'],
            ['true_name','require','姓名必须'],
            ['organization_id','require','请选择团队'],
        ]);
        // 固定角色7（团队客服）
        $data['role_id'] = 7;
        $data['add_time'] = time();
        
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        if (Db::name('account')->where(['account'=>$data['account']])->find()){
            $this->error('账号已存在');
        }
        if ($data['password'] != $data['repassword']) {
            $this->error('两次输入的密码不一致');
        }
        $data['password'] = md5($data['password']);
        $account_model = new Account();
        $accout = $account_model->allowField(true)->save($data);
        if($accout == 1){
            // 加入团队
            $params = [
                'account_id' => $account_model['id'],
                'organization_id' => $data['organization_id'],
                'name' => $account_model['true_name']
            ];
            $res = Db::name('account_member')->insert($params);
            if(!empty($res)){
                $this->success('添加成功');
            }
        }
    }
    public function lists()
    {
        return view();
    }
    public function role()
    {
        return view();
    }
    public function roleList(){
        $page = $this->request->param('page') ?: 1;
        $page_size = $this->request->param('page_size') ?: 15;
        $where = [];
        $menu = MenuService::list('list', where_delete(), [], 'menu_id,menu_pid,menu_name,menu_url,is_unlogin,is_unauth,is_unrate');
        $menu = list_to_tree($menu, 'menu_id', 'menu_pid');
        $menu_ids = array_column($menu, 'menu_id');
        $list = RoleModel::paginate($page_size, false, ['query' => request()->param(),'page'=>$page]);
        $this->success('获取成功','',compact('list','menu','menu_ids'));
    }
    public function roleDelete(){
        $role_id = $this->request->param('role_id');
        // 启动事务
        Db::startTrans();
        try{
            $userAttributesModel = UserAttributesModel::where('role_id',$role_id)->find();
            if($userAttributesModel){
                throw new \Exception("该角色有绑定用户，请解除绑定在删除");
            }
            $res = RoleModel::where('role_id',$role_id)->delete();
            RoleMenusModel::where('role_id',$role_id)->delete();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('删除成功','',$res);
    }
    public function roleAdd(){
        $param = $this->request->param();
        $validate = new Validate([
            ['role_name','require','名称必须'],
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        // 启动事务
        Db::startTrans();
        try{
            $roleModel = new RoleModel();
            $uid = Session::get('uid');
            $param['create_uid']  = $uid;
            // $param['create_time'] = datetime();
            $res = $roleModel->allowField(true)->save($param);
            // 添加菜单
            if (isset($param['menu_ids'])) {
                $roleModel->menus()->saveAll($param['menu_ids']);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
             // 回滚事务
             Db::rollback();
        }
        $this->success('添加成功','',$res);
    }
    public function roleEdit(){
        $params = $this->request->param();
        // 启动事务
        Db::startTrans();
        try{
            $roleModel = new RoleModel();
            $uid = Session::get('uid');
            // $param['role_id'] = $params['role_id'];
            $param['menu_ids'] = $params['menu_ids'];
            $param['role_name'] = $params['role_name'];
            
            $param['update_uid']  = $uid;
            $res = $roleModel->allowField(true)->save($param,['role_id' => $params['role_id']]);
            // 添加菜单
            if (isset($param['menu_ids'])) {
                $info = $roleModel->find($params['role_id']);
                $info = $info->append(['menu_ids']);
                relation_update($info, $info['menu_ids'], $param['menu_ids'], 'menus');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
             // 回滚事务
             Db::rollback();
        }
        $this->success('修改成功','',$res);
    }
    public function roleInfo(){
        $id = $this->request->param('role_id');
        $model = new RoleModel();
        $info = $model->find($id);
        if (empty($info)) {
            $this->error('角色不存在：' . $id);
        }
        $info = $info->append(['menu_ids'])->hidden(['menus'])->toArray();
        $this->success('操作成功','',$info);
    }
    public function menu()
    {
        
        return view();
    }
    public function menuAdd()
    {
        $param = $this->request->param();
        $model = new MenuModel();
        $pk = $model->getPk();

        unset($param[$pk]);
        // var_dump($param);die;
        $uid = Session::get('uid');
        $param['create_uid']  = $uid;
        $param['create_time'] = date('Y-m-d H:i:s',time());

        $add = false;
        $add_arr = ['info' => '信息', 'add' => '添加', 'edit' => '修改', 'dele' => '删除', 'disable' => '是否禁用'];
        // foreach ($add_arr as $k => $v) {
        //     $add_key = '';
        //     $add_key = 'add_' . $k;
        //     if ($param[$add_key] ?? '') {
        //         $add = true;
        //     }
        // }
        
        // 启动事务
        Db::startTrans();
        
        try{
            $menuModel = new MenuModel();
            $menu = $menuModel->allowField(true)->save($param);
            $id = $menuModel->$pk;
            // var_dump($id);die;
            if ($add) {
                if (empty($param['menu_url'])) {
                    exception('请输入菜单链接：应用/控制器/操作');
                }
                $menu_url_pre = substr($param['menu_url'], 0, strripos($param['menu_url'], '/'));

                $add_data = [];
                foreach ($add_arr as $k => $v) {
                    $add_key = '';
                    $add_key = 'add_' . $k;
                    if ($param[$add_key] ?? '') {
                        $add_where = where_delete(['menu_url' => $menu_url_pre . '/' . $k]);
                        // $add_where[] = ['menu_url', '=', $menu_url_pre . '/' . $k];
                        $add_menu = $model->field($pk)->where($add_where)->find();
                        if (empty($add_menu)) {
                            $add_temp = [];
                            $add_temp['menu_pid']    = $id;
                            $add_temp['menu_type']   = SettingService::MENU_TYPE_BUTTON;
                            $add_temp['menu_name']   = $param['menu_name'] . $v;
                            $add_temp['menu_url']    = $menu_url_pre . '/' . $k;
                            $add_temp['create_time'] = date('Y-m-d H:i:s',time());
                            $add_data[] = $add_temp;
                        }
                    }
                }
                if ($add_data) {
                    $model->insertAll($add_data);
                }
                $param['add_data'] = $add_data;
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
             // 回滚事务
             Db::rollback();
        }
        $this->success('添加成功','',[]);

    }
    public function menuEdit(){
        $param = $this->request->param();
        $id = $param['menu_id'];
        $model = new MenuModel();
        $pk = $model->getPk();

        unset($param[$pk]);
        unset($param['delete_time']);
        $uid = Session::get('uid');
        $param['update_uid']  = $uid;
        $param['update_time'] = date('Y-m-d H:i:s',time());
        $param['create_time'] = date('Y-m-d H:i:s',time());
        $menu = $model->find($id);
        $menu->allowField(true)->save($param);
        $this->success('修改成功','',[]);
    }
    public function menuInfo(){
        $param = $this->request->param();
        $id = $param['menu_id'];
        $model = new MenuModel();
        $pk = $model->getPk();

        $menu = $model->find($id)->toArray();
        $this->success('修改成功','',$menu);
    }
    public function menuDel(){
        $param = $this->request->param();
        $id = $param['menu_id'];
        $model = new MenuModel();
        $pk = $model->getPk();
        $res = $model->where($pk, $id)->delete();
        $this->success('删除成功','',$res);
    }
    public function menuList()
    {
        $where = where_delete();
        $data['list']  = MenuService::list('tree', $where);
        $data['tree']  = MenuService::list('tree', where_delete(), [], 'menu_id,menu_pid,menu_name');
        $data['types'] = SettingService::menuTypes();

        $menu = MenuService::list('list', $where, [], 'menu_id');
        $data['count'] = count($menu);

        $this->success('操作成功','',$data);
    }
    /**
     * @Apidoc\Title("用户修改角色")
     * @Apidoc\Method("GET,POST")
     * @Apidoc\Param(ref="idsParam")
     * @Apidoc\Param(ref="app\common\model\system\UserModel\getRoleIdsAttr", field="role_ids")
     */
    public function editrole()
    {
        $param = $this->request->param();
        // var_dump($param);die;
        $model = new Account();
        $info = $model->with('roles')->find($param['id']);
        $info = $info->append(['role_ids']);
        relation_update($info, $info['role_ids'], $param['role_ids'], 'roles');
        $this->success('操作成功','',[]);
    }
    public function getList()
    {
        $where = array_filter(input('post.'));

        $page = max(input('get.page',0),1);

        $status = $this->request->param('status');
        $page_size = $this->request->param('page_size');
        if(empty($page_size )){
            $page_size = 20;
        }
        
        if(!empty($status)){
            // 过滤掉没有启用的账号
            $where['status'] = 1;
        }
        // dump($where);die;
        // $where['role_id'] = ['in',[1,2,3,4,5,6,7]];
        $account = new \app\common\model\Account();
        // $total = Db::name('account')->where($where)->count();
        // $rows = Db::name('account')->where($where)->field('password',true)->page($page,$page_size)->select();
        $total = $account->where($where)->count();
        $rows = $account->with('accountMember,roles')->where($where)->field('password',true)->page($page,$page_size)->select();
        $status_txt = Account::$status_txt;
        $role_txt = Account::$role_txt;
        //return $role_txt;
        foreach ($rows as $key => $row) {
            $rows[$key]['add_time'] = date('Y-m-d H:i',$row['add_time']);
            $rows[$key]['last_login_time'] = date('Y-m-d H:i',$row['last_login_time']);
            $rows[$key]['status_txt'] = $status_txt[$row['status']];
            $rows[$key]['role'] = $role_txt[$row['role_id']];
        }
        $data= [
            'rows'      => $rows,
            'total'     => $total,
            'page_size' => $page_size,
            'page'      => $page
        ];
        $model = new RoleModel();
        $data['role'] = $model->field('role_id,role_name')->where(where_delete())->select()->toArray();
        $this->success('获取成功','',$data);
    }
    public function setStatus()
    {
        $where['id'] = input('post.id');
        $data['status'] = input('post.status');
        $affected = Db::name('account')->where($where)->update($data);
        //return $affected;
        if ($affected) {
            return ['code' => 1, 'msg' => '修改成功'];
        } else {
            return ['code' => 0, 'msg' => '修改失败'];
        }
    }
    /**
     * 只查看自己的订单
     */
    public function setOrderStatus()
    {
        $where['id'] = input('post.id');
        $data['order_status'] = input('post.order_status');
        $affected = Db::name('account')->where($where)->update($data);
        if ($affected) {
            return ['code' => 1, 'msg' => '修改成功'];
        } else {
            return ['code' => 0, 'msg' => '修改失败'];
        }
    }
    /**
     * 设置权限和姓名
     */
    public function setRules()
    {
        $where['id'] = input('post.id');
        $data = [];
        if(input('post.rules')){
            $data['rules'] = input('post.rules');
        }
        if(input('post.true_name')){
            $data['true_name'] = input('post.true_name');
        }
        if(input('post.password')){
            $data['password'] = md5(input('post.password'));
        }
        $affected = Db::name('account')->where($where)->update($data);
        if ($affected) {
            return ['code' => 1, 'msg' => '修改成功'];
        } else {
            return ['code' => 0, 'msg' => '修改失败'];
        }
    }
    public function getSalers()
    {
        $where = [
            'role_id'   => ['in',[1,6,7]],
            'status'    => 1
        ];
        $accts = Db::name('account')->where($where)->field('id,true_name')->select();
        foreach ($accts as $acct) {
            $row = [
                'id'     => $acct['id'],
                'val'    => $acct['true_name'],
            ];
            $rows[] = $row;
        }
        $data['rows'] = $rows;
        $this->success('获取成功','',$data);
    }
    public function setting()
    {
        $where = [
            'id'    => Session::get('uid')
        ];
        $acct = Db::name('account')->where($where)->find();
        $this->assign('acct', $acct);
        return view();
    }
    public function setHandle()
    {
        //数据验证
        $data = input('post.');

        $validate = new Validate([
            ['password','require|min:6','新密码必须|密码长度不能低于6位'],
            ['repassword','require','重复密码必须'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        if ($data['password'] != $data['repassword']) {
            $this->error('两次输入的密码不一致');
        }

        $info['password'] = md5($data['password']);
        if (Db::name('account')->where('id',Session::get('uid'))->update($info)) {
            //注销
            Session::delete('uid','think');
            Session::delete('account','think');
            $this->success('密码修改成功');
        } else {
            $this->success('修改失败');
        }
    }
    public function pageLogList()
    {
        return view();
    }
    public function getPageLogList()
    {
        $where = array_filter(input('post.'));
        if (!empty($where['acct_name'])) {
            $where['acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }

        $page = max(input('get.page',0),1);
        $page_size = 15;

        $model = Db::name('page_log');
        $total = $model->where($where)->count();
        $rows = $model->where($where)
                    ->page($page, $page_size)
                    ->select();
        foreach($rows as &$row) {
            $row['add_time'] = date('Y-m-d ; H:i',$row['add_time']);
        }
        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];

        $this->success('获取成功','',$data);

    }
    /**
     * 获取账户信息
     */
    public function getUserInfo(){
        // 获取个人信息
        $id = Session::get('uid');
        $user_info = Db::name('account')->where('id',$id)->find();
        $this->success('获取成功','',$user_info);
    }
}